package com.xpp.yanpicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.xpp.yanpicturebackend.config.CosClientConfig;
import com.xpp.yanpicturebackend.exception.BusinessException;
import com.xpp.yanpicturebackend.exception.ErrorCode;
import com.xpp.yanpicturebackend.manager.CosManager;
import com.xpp.yanpicturebackend.model.dto.file.UploadPicturesResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param inputSource      输入源
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPicturesResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1. 校验对象
        validPicture(inputSource);

        // 2. 图片上传地址
        String uuid = RandomUtil.randomString(6);
        String originalFilename = getOriginalFilename(inputSource);
        // 拼接文件上传路径
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        try {
            // 3. 创建临时文件，获取文件到服务器
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源
            processFile(inputSource, file);
            // 4. 对象存储, 上传到 COS
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 5. 获取图片信息对象, 封装返回结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取图片处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                // 获取压缩之后的图片信息
                CIObject compressedCiObject = objectList.get(0);
                // 缩略图默认等于压缩图
                CIObject thumbnailObject = compressedCiObject;
                if (objectList.size() > 1){
                    thumbnailObject = objectList.get(1);
                }

                // 封装压缩图的返回结果
                return buildResult(originalFilename, compressedCiObject, thumbnailObject, imageInfo);
            }
            // 返回封装好的对象
            return buildResult(originalFilename, uploadPath, file, imageInfo);

        } catch (Exception e) {
            log.error("file upload error, filepath = " + uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 6. 清理临时文件
            deleteTempFile(file);
        }
    }


    /**
     * 处理输入源产生临时文件
     *
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws IOException;

    /**
     * 获取输入源的原始文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 校验输入源
     *
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 封装返回结果
     *
     * @param originalFilename
     * @param uploadPath
     * @param file
     * @param imageInfo        图片信息对象
     * @return
     */
    private UploadPicturesResult buildResult(String originalFilename, String uploadPath, File file, ImageInfo imageInfo) {
        // 封装返回对象
        String format = imageInfo.getFormat();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        UploadPicturesResult uploadPicturesResult = new UploadPicturesResult();
        uploadPicturesResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPicturesResult.setName(FileUtil.mainName(originalFilename));
        uploadPicturesResult.setPicSize(FileUtil.size(file));
        uploadPicturesResult.setPicWidth(picWidth);
        uploadPicturesResult.setPicHeight(picHeight);
        uploadPicturesResult.setPicScale(picScale);
        uploadPicturesResult.setPicFormat(format);
        uploadPicturesResult.setPicColor(imageInfo.getAve());
        return uploadPicturesResult;
    }

    /**
     * 封装压缩后的返回结果
     *
     * @param originalFilename
     * @param compressedCiObject
     * @param thumbnailObject
     * @return
     */
    private UploadPicturesResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailObject, ImageInfo imageInfo) {
        // 封装返回对象
        String format = compressedCiObject.getFormat();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        UploadPicturesResult uploadPicturesResult = new UploadPicturesResult();
        // 设置压缩后的原图地址
        uploadPicturesResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        // 设置缩略图地址
        uploadPicturesResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailObject.getKey());
        uploadPicturesResult.setName(FileUtil.mainName(originalFilename));
        uploadPicturesResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPicturesResult.setPicWidth(picWidth);
        uploadPicturesResult.setPicHeight(picHeight);
        uploadPicturesResult.setPicScale(picScale);
        uploadPicturesResult.setPicFormat(format);
        uploadPicturesResult.setPicColor(imageInfo.getAve());
        return uploadPicturesResult;
    }

    /**
     * 清理临时文件
     *
     * @param tempFile
     */
    private static void deleteTempFile(File tempFile) {
        if (tempFile == null) {
            return;
        }
        // 删除临时文件
        boolean delete = tempFile.delete();
        if (!delete) {
            log.error("file delete error,file = {}", tempFile);
        }
    }

}
